//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package client_cfg_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas-org/api-server/config"
	"atomgit.com/openlinksaas-org/api-server/dao/client_cfg_dao"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/client_cfg_api"
	"go.uber.org/zap"
)

type ClientCfgApiImpl struct {
	client_cfg_api.UnimplementedClientCfgApiServer
	servCfg   *config.ServerConfig
	errLogger *zap.Logger
}

func NewClientCfgApiImpl(servCfg *config.ServerConfig, errLogger *zap.Logger) *ClientCfgApiImpl {
	return &ClientCfgApiImpl{
		servCfg:   servCfg,
		errLogger: errLogger,
	}
}

func (apiImpl *ClientCfgApiImpl) GetCfg(ctx context.Context, req *client_cfg_api.GetCfgRequest) (*client_cfg_api.GetCfgResponse, error) {
	menuItemList, err := client_cfg_dao.ExtraMenuDao.List(ctx)
	if err != nil {
		return nil, err
	}
	itemList := []*client_cfg_api.ExtraMenuItem{}
	for _, menuItem := range menuItemList {
		itemList = append(itemList, menuItem.ToExtraMenuItem())
	}

	return &client_cfg_api.GetCfgResponse{
		ItemList:              itemList,
		EnableAdmin:           apiImpl.servCfg.Admin.Enable,
		AtomGitClientId:       apiImpl.servCfg.AtomGit.ClientId,
		GiteeClientId:         apiImpl.servCfg.Gitee.ClientId,
		GitCodeClientId:       apiImpl.servCfg.GitCode.ClientId,
		ServerTime:            time.Now().UnixNano() / 1e6,
		EnableUserMail:        apiImpl.servCfg.ClientCfg.MaxMailCountPerUser > 0 && apiImpl.servCfg.ClientCfg.MaxMailAccountPerUser > 0 && apiImpl.servCfg.ClientCfg.UserMailDomain != "",
		MaxMailCountPerUser:   apiImpl.servCfg.ClientCfg.MaxMailCountPerUser,
		MaxMailAccountPerUser: apiImpl.servCfg.ClientCfg.MaxMailAccountPerUser,
		UserMailDomain:        apiImpl.servCfg.ClientCfg.UserMailDomain,
		ServHttpAddr:          apiImpl.servCfg.WebAddr,
	}, nil
}

func (apiImpl *ClientCfgApiImpl) ReportError(ctx context.Context, req *client_cfg_api.ReportErrorRequest) (*client_cfg_api.ReportErrorResponse, error) {
	if apiImpl.errLogger != nil {
		apiImpl.errLogger.Info(req.ErrData)
	}
	return &client_cfg_api.ReportErrorResponse{}, nil
}
